﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Web;
using System.Web.Script.Serialization;

namespace WebApplication1.classes.Core.Chrome.Bookmarks.Wrapper {
    public class BookmarkJsonConverter : JavaScriptConverter {
        
        #region Overrides of JavaScriptConverter

        public override object Deserialize( IDictionary<string, object> dictionary, Type type, JavaScriptSerializer serializer ) {
            if (dictionary == null){
                return null;
            }
            var bookmark = new Bookmark();
            bookmark.name = serializer.ConvertToType<string>(dictionary["name"]);
            
            return bookmark;
        }

        public override IDictionary<string, object> Serialize( object obj, JavaScriptSerializer serializer ) {
            var bookmark = obj as Bookmark;
            var result = new Dictionary<string, object>();
            if (bookmark != null){
                result.Add("name",bookmark.name);
                result.Add("unid", bookmark.uniqueIdentifier);

                var childrenList = bookmark.childrenToList();
                var childrenArray = childrenList.ToArray();
                var serializedChildren =  serializer.Serialize(childrenArray);
                result.Add("children",serializedChildren);
            }

            return result;
        }

        public override IEnumerable<Type> SupportedTypes {
            get { 
                return new List<Type>(new Type[]{typeof(Bookmark)});
            }
        }

        #endregion
    }
}